<?php//company 1代表华夏人寿，2代表天安人寿，3代表太平养老header("Content-Type:text/html; charset=UTF-8");class ShouxianController extends Controller{    /**     * 航综的报文格式     * 投保     */    public function actionHangInsure() {        $data = trim(file_get_contents("php://input"));        if (empty($data)) {            echo $xml_content = '<?xml version="1.0" encoding="UTF-8"?>    <ApplyResponse>      <TransData>        <ResultStatus>01</ResultStatus>        <ResultMsg>无参数</ResultMsg>      </TransData>    </ApplyResponse>';            die();        }        $this->log("同程投保申请航综报文格式：".$data);        $xml_parser = xml_parser_create();        if(!xml_parse($xml_parser,$data,true)){            xml_parser_free($xml_parser);            echo $xml_content = '<?xml version="1.0" encoding="UTF-8"?>    <ApplyResponse>      <TransData>        <ResultStatus>01</ResultStatus>        <ResultMsg>参数错误</ResultMsg>      </TransData>    </ApplyResponse>';            die();        }        $data = simplexml_load_string($data);        $data = json_decode(json_encode((array) $data), true);        $third_party_code = $data['ProductCode'];        $model = CsProductCode::model()->findByAttributes(array('third_party_code'=>$third_party_code));        if (!$model) {            echo $xml_content = '<?xml version="1.0" encoding="UTF-8"?>    <ApplyResponse>      <TransData>        <ResultStatus>01</ResultStatus>        <ResultMsg>产品不存在</ResultMsg>      </TransData>    </ApplyResponse>';            die();        }        //判断成功的请求是否重复提交,        $dist = ImportinfoF::model()->findByAttributes(array(            'cWaterNo'=>$data['CWaterNo'],            'cooperation'=>'tongcheng'        ));        if($dist->retCode == "00") {            //如果重复  则返回已投保信息            $xml_content = '<?xml version="1.0" encoding="UTF-8"?>            <ApplyResponse>                <CWaterNo>'.$dist->cWaterNo.'</CWaterNo>                <endDate>'.$dist->endDate.'</endDate>                <policyNum>'.$dist->policyNum.'</policyNum>                <retCode>'.$dist->retCode.'</retCode>                <retDesc>'.$dist->retDesc.'</retDesc>                <startDate>'.$dist->startDate.'</startDate>                <policyStatus>'.$dist->policyStatus.'</policyStatus>                <RealDate>'.date('Y-m-d H:i:s',$dist->realDate).'</RealDate>                <strLockKey>'.$dist->strLockKey.'</strLockKey>                <company>'.$dist->in_company.'</company>            </ApplyResponse>            ';            echo $xml_content;        } else {            //投保人            $holder = new PolicyholdersF();            $holder->ApplicantName = $data['ApplicantName'];            $holder->ApplicantZJNum = $data['ApplicantZJNum'];            $holder->ApplicantZJType = $data['ApplicantZJType'];            $holder->ApplicantMobile = $data['ApplicantMobile']?$data['ApplicantMobile']:'';            $holder->ApplicantType = $data['ApplicantType'];            if($data['ApplicantBirthday']){                $holder->birthday = date('Y-m-d',strtotime($data['ApplicantBirthday']));            }else{                $holder->birthday = $this->birthIDCard($data['ApplicantZJNum']);            }            if($data['ApplicantSex']){                $holder->sex = $data['ApplicantSex'];            }else{                $holder->sex = $this->sexIDCard($data['ApplicantZJNum']);            }            $holder->ApplicantEmail = $data['ApplicantEmail'];            $holder->create_time = time();            $holder->save(false);            //被保人列表信息            $InsuedInfo = $data['InsuedInfoInfoList'];            //存入出保交易流水表   后续投保使用            $approval = new ApprovaltransF();            $approval->TransID = $data['CWaterNo'];            $approval->MerchantNo = 'tongcheng';            $approval->TransDate = date('Ymd',time());            $approval->TransTime = date('His',time());            $approval->EffectDate = date('Ymd',strtotime($data['StartDate']));            $approval->EffectTime = date('His',strtotime($data['StartDate']));            $approval->proposer_id = $holder->id;            $approval->ProductCode = $data['ProductCode'];            $approval->rationType = $data['ProductCode'];            $approval->riskCode = '';            $approval->premium = $data['Premium'];            $approval->startDate = $data['StartDate'];            $approval->waterNo = $data['CWaterNo'];            $approval->OrderID = $data['OrderNo'];            $approval->trip = $data['AviationRiskInfo']['FlightNum'];            $approval->date = $data['AviationRiskInfo']['DepartureDate'];            $approval->endDate = $data['EndDate'];            $approval->inputDate = $data['InputedDate'];            $approval->holderNum = count($InsuedInfo);            $approval->issuedDate = $data['IssuedDate'];            $approval->DepartureCity = $data['AviationRiskInfo']['DepartureCity'];            $approval->ArrivalCity = $data['AviationRiskInfo']['ArrivalCity'];            $approval->CarNo = $data['carNo'];            $approval->CarNum = $data['carNum'];            $approval->address = $data['address'];            $approval->school = $data['school'];            $approval->class = $data['class'];            $approval->createTime = time();            $approval->save(false);            //被保人            foreach ($InsuedInfo as $value) {                $Insued = new InsuredinfoF();                $Insued->approvaltrans_id = $approval->id;                $Insued->InsuedName = $value['InsuedName'];                $Insued->InsuedZJNo = $value['InsuedZJNo'];                $Insued->InsuedZJType = $value['InsuedZJType'];                $Insued->InsuedMobile = $value['InsuedMobile']?$value['InsuedMobile']:'';                if($value['InsuedBirthday']){                    $Insued->birthday = date('Y-m-d',strtotime($value['InsuedBirthday']));                }else{                    $Insued->birthday = $this->birthIDCard($value['InsuedZJNo']);                }                if($value['InsuedSex']){                    $Insued->sex = $value['InsuedSex'];                }else{                    $Insued->sex = $this->sexIDCard($value['InsuedZJNo']);                }                $Insued->insRelationApp = $value['insuredPolRelation']?$value['insuredPolRelation']:'99';                $Insued->create_time = time();                $Insued->save(false);            }            //根据产品动态分配            $thirdPartyCode = $data['ProductCode'];  //提供给第三方的产品编号            $res = $this->getTargetCompany($thirdPartyCode);            $data['waterNo'] = $data['CWaterNo'];            $data['cooperation'] = 'tongcheng';            $data['insure_product_code'] = $res['product_code'];            $data['third_party_code'] = $data['ProductCode'];            $insure_company = $res['in_company'];            if($insure_company == 2) { //天安                $this->TA($approval->id,$data,'hang');            } else if($insure_company == 1) { //华夏                $this->HX($approval->id,$data,'hang');            } else if($insure_company == 3) { //太平                $this->TP($approval->id,$data,'hang');            }        }    }    /*     * 火综的报文格式     * 投保     */    public function actionHuoInsure() {        // 接收投保报文        $data = trim(file_get_contents("php://input"));        if(!$data){            echo '{"waterNo":"","retCode":"11","retDesc":"无参数","policyNum":"","transTime":""}';die;        }        // 日志记录        $this->log("同程投保申请火综报文格式：".$data);        $data = json_decode($data, true);        if(!$data){            echo '{"waterNo":"","retCode":"11","retDesc":"参数不是json格式","policyNum":"","transTime":""}';die;        }        $third_party_code = $data['rationType'];        $model = CsProductCode::model()->findByAttributes(array('third_party_code'=>$third_party_code));        if (!$model) {            echo '{"waterNo":"","retCode":"11","retDesc":"产品不存在","policyNum":"","transTime":""}';die;        }        //校验参数        $falsemsg=array(   'waterNo' => $data['waterNo'],            'retCode' => '11',            'retDesc'=>'',            'policyNum'=>'',            'transTime'=>'',        );        if(!$data['cooperation']){            $falsemsg['retDesc']="缺少参数:cooperation";            die($this->JSON($falsemsg));        }        $get = array('waterNo'=>$data['waterNo'],            'startDate'=>$data['startDate'],            'rationType'=>$data['rationType'],            'insuredName'=>$data['insuredList'][0]['insuredName'],            'insuredIdentifyType'=>$data['insuredList'][0]['insuredIdentifyType'],            'insuredIdentifyNumber'=>$data['insuredList'][0]['insuredIdentifyNumber'],            'policyName'=>$data['policyName'],            'policyIdentifyType'=>$data['policyIdentifyType'],            'policyIdentifyNumber'=>$data['policyIdentifyNumber'],        );        //非空判断        foreach ($get as $key => $value) {            if($value == ''){                $falsemsg['retDesc']="缺少参数:".$key;                die($this->JSON($falsemsg));            }        }        if($data['policyIdentifyType']!='01'){//投保人身份证            if(!$data['policyBirthday']){                $falsemsg['retDesc']="缺少参数:policyBirthday";                die($this->JSON($falsemsg));            }            if(!$data['policySex']){//投保人性别                $falsemsg['retDesc']="缺少参数:policySex";                die($this->JSON($falsemsg));            }            //格式判断        }elseif(!$this->idcard($data['policyIdentifyNumber'])){            $falsemsg['retDesc']="参数policyIdentifyNumber格式不正确";            die($this->JSON($falsemsg));        }        if ($data['policyBirthday'] && !strtotime($data['policyBirthday'])) {            $falsemsg['retDesc']="参数policyBirthday格式不正确";            die($this->JSON($falsemsg));        }        if(!preg_match('/^\d*$/',$data['rationType'])) {            $falsemsg['retDesc'] = "参数rationType格式不正确";            die($this->JSON($falsemsg));        }        if(!in_array($data['policyIdentifyType'],array('01','02','03','09','11'))){            $falsemsg['retDesc']="参数policyIdentifyType格式不正确";            die($this->JSON($falsemsg));        }        if(!in_array($data['policySex'],array('01','02',''))){            $falsemsg['retDesc']="参数policySex格式不正确";            die($this->JSON($falsemsg));        }        //被保人列表信息        $InsuedInfo = $data['insuredList'];        foreach ($InsuedInfo as $key => $value) {            $k = $key+1;            if($value['insuredIdentifyType']!='01'){                if(!$value['insuredBirthday']){                    die('{"waterNo":"'.$data['waterNo'].'","retCode":"11","retDesc":"缺少参数:第'.$k.'被保险人insuredBirthday","policyNum":"","transTime":""}');                }                if(!$value['insuredSex']){                    die('{"waterNo":"'.$data['waterNo'].'","retCode":"11","retDesc":"缺少参数:第'.$k.'被保险人insuredSex","policyNum":"","transTime":""}');                }            }elseif (!$this->idcard($value['insuredIdentifyNumber'])) {                $falsemsg['retDesc']="第".$k."被保险人参数insuredIdentifyNumber格式不正确";                die($this->JSON($falsemsg));            }            if ($value['insuredBirthday'] && !strtotime($value['insuredBirthday'])) {                $falsemsg['retDesc']="第".$k."被保险人参数insuredBirthday格式不正确";                die($this->JSON($falsemsg));            }            if (!in_array($value['insuredSex'],array('01','02',''))) {                $falsemsg['retDesc']="第".$k."被保险人参数insuredSex格式不正确";                die($this->JSON($falsemsg));            }            if(!in_array($value['insuredPolRelation'],array('01','10','40','50','13','99',''))){                $falsemsg['retDesc']="第".$k."被保险人参数insuredPolRelation格式不正确";                die($this->JSON($falsemsg));            }        }        //判断是否重复提交        $dist = ImportinfoF::model()->findByAttributes(array(            'cWaterNo'=>$data['waterNo'],            'cooperation'=>$data['cooperation']        ));        if($dist->retCode == '00') {            //如果重复  则返回已投保信息            $return = array();            $return['waterNo'] = $dist->cWaterNo;            $return['retCode'] = $dist->retCode;            $return['retDesc'] = $dist->retDesc;            $return['policyNum'] = $dist->policyNum;            $return['transTime'] = date('Y-m-d H:i:s',$dist->realDate);            $return['epolicyAddress'] = $dist->epolicyAddress;            $return['company'] = $dist->in_company;            echo $this->JSON($return);        } else {            //投保人            $holder = new PolicyholdersF();            $holder->ApplicantName = $data['policyName'];            $holder->ApplicantZJNum = $data['policyIdentifyNumber'];            $holder->ApplicantZJType = $data['policyIdentifyType'];            $holder->ApplicantMobile = $data['policyMobile']?$data['policyMobile']:'';            $holder->ApplicantType = '1';            if($data['policyBirthday']){                $holder->birthday = date('Y-m-d',strtotime($data['policyBirthday']));            }else{                $holder->birthday = $this->birthIDCard($data['policyIdentifyNumber']);            }            if($data['policySex']){                $holder->sex = $data['policySex'];            }else{                $holder->sex = $this->sexIDCard($data['policyIdentifyNumber']);            }            $holder->ApplicantEmail = $data['policyEmail'];            $holder->create_time = time();            $holder->save(false);            //存入出保交易流水表   后续投保使用            $approval = new ApprovaltransF();            $approval->TransID = $data['waterNo'];            $approval->MerchantNo = $data['cooperation'];            $approval->TransDate = date('Ymd',time());            $approval->TransTime = date('His',time());            $approval->EffectDate = date('Ymd',strtotime($data['startDate']));            $approval->EffectDate = date('His',strtotime($data['startDate']));            $approval->proposer_id = $holder->id;            $approval->ProductCode = $data['rationType'];            $approval->rationType = $data['rationType'];            $approval->riskCode = '';            $approval->premium = $data['premium'];            $approval->startDate = date('Y-m-d H:i:s',strtotime($data['startDate']));            $approval->waterNo = $data['waterNo'];            $approval->OrderID = $data['orderNo'];            $approval->trip = $data['trip'];            $approval->date = $data['date'];            if($data['endDate']){                $approval->endDate = date('Y-m-d H:i:s',strtotime($data['endDate']));            }else{                $approval->endDate = date('Y-m-d H:i:s',strtotime($data['startDate'])+60*60*24*7);            }            $approval->inputDate = date('Y-m-d H:i:s',time());            $approval->holderNum = count($InsuedInfo);            $approval->issuedDate = date('Y-m-d H:i:s',time());            $approval->DepartureCity = $data['departureCity'];            $approval->ArrivalCity = $data['arrivalCity'];            $approval->CarNo = $data['carNo'];            $approval->CarNum = $data['carNum'];            $approval->address = $data['address'];            $approval->school = $data['school'];            $approval->class = $data['class'];            $approval->createTime = time();            $approval->save(false);            //被保人            foreach ($InsuedInfo as $value) {                $Insued = new InsuredinfoF();                $Insued->approvaltrans_id = $approval->id;                $Insued->InsuedName = $value['insuredName'];                $Insued->InsuedZJNo = $value['insuredIdentifyNumber'];                $Insued->InsuedZJType = $value['insuredIdentifyType'];                $Insued->InsuedMobile = $value['insuredMobile']?$value['insuredMobile']:'';                $idcard = $value['insuredIdentifyNumber'];                if($value['insuredBirthday']){                    $Insued->birthday = date('Y-m-d',strtotime($value['insuredBirthday']));                }else{                    $Insued->birthday = $this->birthIDCard($idcard);                }                if($value['insuredSex']){                    $Insued->sex = $value['insuredSex'];                }else{                    $Insued->sex = $this->sexIDCard($idcard);                }                $Insued->insRelationApp = $value['insuredPolRelation']?$value['insuredPolRelation']:'99';                $Insued->create_time = time();                $Insued->save(false);            }            //根据产品动态分配            $thirdPartyCode = $data['rationType'];  //提供给第三方的产品编号            $res = $this->getTargetCompany($thirdPartyCode);            $data['cooperation'] = 'tongcheng';            $data['insure_product_code'] = $res['product_code'];            $data['third_party_code'] = $data['rationType'];            $insure_company = $res['in_company'];            if($insure_company == 2) { //天安                $this->TA($approval->id,$data,'huo');            } else if($insure_company == 1) { //华夏                $this->HX($approval->id,$data,'huo');            } else if($insure_company == 3) { //太平                $this->TP($approval->id,$data,'huo');            }        }    }    /**     * 投保太平     */    public function TP($id,$data,$insureType=null) {        $uri =  Yii::app()->params['Taiping_toubao'];        $req_str = $this->TPxml($id,$data);        $startime=microtime(true);        $ret = $this->request_by_curl($uri,$req_str);        $endtime=microtime(true);        $alltime=$endtime-$startime;        $this->log("太平投保申请报文：".$req_str);        $this->log("太平投保返回报文：".$ret);        $this->log("太平投保反应时间（秒）：".$alltime);        $result = json_decode($ret);        $import = new ImportinfoF();        $import->approvaltrans_id = $id;        $import->cWaterNo = $data['waterNo'];        $import->cooperation = $data['cooperation'];        $return = array(            'waterNo' => $data['waterNo'],            'retCode' => '',            'retDesc' => '',            'policyNum' => '',            'transTime' => '',            'epolicyAddress' => '',        );        if( $result ) {            if ($result->retCode == "0000") {                $import->policyNum = $result->policyNo;                $import->retCode = "00";                $import->retDesc = $result->returnMsg;                $import->startDate = $result->startDate;                $import->endDate = $result->endDate;                $import->policyStatus = $result->returnMsg;                $import->realDate = strtotime($result->transTime);                $import->strLockKey = $data['StrLockKey'];                $import->orderNo = $data['orderNo'];                $import->epolicyAddress = $result->epolicyAddress;                $import->in_company = "3";                $return['retCode'] = "00";                $return['retDesc'] = $result->returnMsg;                $return['policyNum'] = $result->policyNo;                $return['transTime'] = $result->transTime;                $return['epolicyAddress'] = $result->epolicyAddress;                //新增分保记录                $third_party_code = $data['third_party_code'];                $model = CsProductCode::model()->findByAttributes(array('third_party_code'=>$third_party_code,'in_company'=>3));                $model->insure_number += 1;                $model->save();            } else {                $import->retCode = "11";                $import->retDesc = $result->returnMsg;                $import->startDate = $data['StartDate'];                $import->endDate = $data['EndDate'];                $import->policyStatus = "失败";                $import->realDate = time();                $import->strLockKey = $data['StrLockKey'];                $import->orderNo = $data['OrderNo'];                $import->in_company = "3";                $return['retCode'] = "11";                $return['retDesc'] = $result->returnMsg;            }        }else{            $import->retCode = "11";            $import->retDesc = '核心接口连接失败，请联系管理员';            $import->policyStatus = "失败";            $import->realDate = time();            $import->in_company = "3";            $return['retCode'] = "11";            $return['retDesc'] = '核心接口连接失败，请联系管理员';        }        $import->createTime = time();        $import->save(false);        $return['company'] = "3";        $company = 3;        if ($insureType == 'huo') {            echo $return_msg = $this->JSON($return);        }        if ($insureType == 'hang') {            echo $return_msg = $this->setInsureXml($data,$result,$company);        }        $this->log("同程承保返回报文：".$return_msg);    }    /**     * 投保华夏     */    public function HX($id,$data,$insureType=null) {        $uri =  Yii::app()->params['Huaxia_toubao'];        $req_param = $this->HXparam($id,$data);        $startime=microtime(true);        $ch = curl_init();        curl_setopt($ch,CURLOPT_URL,$uri);        curl_setopt($ch,CURLOPT_POST, 1);        $request = http_build_query($req_param);        curl_setopt($ch,CURLOPT_POSTFIELDS, $request);        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);        $response = curl_exec($ch);        curl_close($ch);        $endtime=microtime(true);        $alltime=$endtime-$startime;        $this->log("华夏投保申请报文：".json_encode($req_param));        $this->log("华夏投保返回报文：".$response);        $this->log("华夏投保反应时间（秒）：".$alltime);        $result = json_decode($response);        $import = new ImportinfoF();        $import->approvaltrans_id = $id;        $import->cWaterNo = $data['waterNo'];        $import->cooperation = $data['cooperation'];        $return = array(            'waterNo' => $data['waterNo'],            'retCode' => '',            'retDesc' => '',            'policyNum' => '',            'transTime' => '',            'epolicyAddress' => '',        );        if( $result ) {            if ($result->retCode == "00") {                $import->policyNum = $result->policyNum;                $import->retCode = "00";                $import->retDesc = $result->retDesc;                $import->startDate = $data['StartDate'];                $import->endDate = $data['EndDate'];                $import->policyStatus = "成功";                $import->realDate = strtotime($result->transTime);                $import->strLockKey = NULL;                $import->orderNo = $data['orderNo'];                $import->epolicyAddress = $result->epolicyAddress;                $import->in_company = "1";                $return['retCode'] = $result->retCode;                $return['retDesc'] = $result->retDesc;                $return['policyNum'] = $result->policyNum;                $return['transTime'] = $result->transTime;                $return['epolicyAddress'] = $result->epolicyAddress;                //新增分保记录                $third_party_code = $data['third_party_code'];                $model = CsProductCode::model()->findByAttributes(array('third_party_code'=>$third_party_code,'in_company'=>1));                $model->insure_number += 1;                $model->save();            } else {                $import->retCode = "11";                $import->retDesc = $result->retDesc;                $import->startDate = NULL;                $import->endDate = NULL;                $import->policyStatus = "失败";                $import->realDate = time();                $import->strLockKey = NULL;                $import->orderNo = $data['orderNo'];                $import->in_company = "1";                $return['retCode'] = "11";                $return['retDesc'] = $result->retDesc;            }        }else{            $import->retCode = "11";            $import->retDesc = '核心接口连接失败，请联系管理员';            $import->policyStatus = "失败";            $import->realDate = time();            $import->in_company = "1";            $return['retCode'] = "11";            $return['retDesc'] = '核心接口连接失败，请联系管理员';        }        $import->createTime = time();        $import->save(false);        $return['company'] = "1";        $company = 1;        if ($insureType == 'huo') {            echo $return_msg = $this->JSON($return);        }        if ($insureType == 'hang') {            echo $return_msg = $this->setInsureXml($data,$result,$company);        }        $this->log("同程承保返回报文：".$return_msg);    }    public function HXparam($id,$data) {        $appData = ApprovaltransF::model()->findByPk($id);        $holderData = PolicyholdersF::model()->findByPk($appData->proposer_id);        $InsuedInfo = InsuredinfoF::model()->findAllByAttributes(array("approvaltrans_id"=>$appData->id));        $insuredList = '';        $rationType = $data['insure_product_code'];        foreach ($InsuedInfo as $key => $value) {            $insuredList .= '{                 "insuredName":"'.$value['InsuedName'].'",                 "insuredSex":"'.$value['sex'].'",                 "insuredIdentifyType":"'.$value['InsuedZJType'].'",                 "insuredIdentifyNumber":"'.$value['InsuedZJNo'].'",                 "insuredBirthday":"'.date('Ymd',strtotime($value['birthday'])).'",                 "insuredMobile":"'.$value['InsuedMobile'].'",                 "insuredAddress":"",                 "insuredPolRelation":"'.$value['insRelationApp'].'",                 "insuredBenRelation":"'.$value['insRelationApp'].'",                 "insuredEmail":"",                 "insuredZipCode":""               }';            if ($key > 0 && $key < (count($InsuedInfo)-1)) {                $insuredList .= ",";            }        }        $json = '{            "cooperation":"'.'tongcheng'.'",            "rationType":"'.$rationType.'",            "orderNo":"'.$appData['OrderID'].'",            "waterNo":"'.$appData['TransID'].'",            "startDate":"'.date('Y-m-d H:i:s',strtotime($appData['startDate'])).'",            "endDate":"'.date('Y-m-d H:i:s',strtotime($appData['endDate'])).'",            "policyName":"'.$holderData['ApplicantName'].'",            "policySex":"'.$holderData['sex'].'",            "policyIdentifyType":"'.$holderData['ApplicantZJType'].'",            "policyIdentifyNumber":"'.$holderData['ApplicantZJNum'].'",            "policyBirthday":"'.date('Ymd',strtotime($holderData['birthday'])).'",            "policyMobile":"'.$holderData['ApplicantMobile'].'",            "policyAddress":"",            "policyEmail":"",            "policyZipCode":"",            "insuredList":[                '.$insuredList.'             ],            "FlightNo":"'.$appData['trip'].'",            "date":"'.date('Ymd',strtotime($appData['date'])).'"            }';        $json = json_encode(json_decode($json, true), JSON_UNESCAPED_UNICODE);        $nonce = substr(md5(microtime(1)), 0, 20);        $timestamp = str_replace(".", "", microtime(1));        $params['uid'] = "adpt_tongcheng";        $params['timestamp'] = $timestamp;        $params["nonce"] = $nonce;        $params["data"] = $json;        $signString = $this->getLinkString($params);        $key = Yii::app()->params['Huaxia_key'];;        $signature = md5($signString.$key);        $params['signature'] = $signature;        return $params;    }    function getLinkString($params)    {        $params = array_filter($params); // 过滤空值        unset($params['signature']); // 去掉签名,如有        ksort($params);        $peers = [];        foreach ($params as $k => $v) {            $peers[] = "$k=$v";        }        return implode("&", $peers);    }    private function setInsureXml($data,$result,$company) {        if ($company == 1) {            $policyNum = $result->policyNum;            $RealDate = $result->transTime;        } else {            $policyNum = $result->policyNo;            $RealDate = date("Y-m-d H:i:s");        }        if ($company == 3) {            $retCode = ($result->retCode=='0000'?'00':'11');            $retDesc = $result->returnMsg;        } else {            $retCode = ($result->retCode=='00'?'00':'11');            $retDesc = $result->returnMsg;        }        if ($company == 1) {            $retDesc = $result->retDesc;        }        $RealDate = $result->transTime;        $xml_content = '<?xml version="1.0" encoding="UTF-8"?>            <ApplyResponse>                <CWaterNo>'.$data["CWaterNo"].'</CWaterNo>                <endDate>'.$data["EndDate"].'</endDate>                <policyNum>'.$policyNum.'</policyNum>                <retCode>'.$retCode.'</retCode>                <retDesc>'.$retDesc.'</retDesc>                <startDate>'.$data["StartDate"].'</startDate>                <policyStatus>'.$retDesc.'</policyStatus>                <RealDate>'.$RealDate.'</RealDate>                <strLockKey>'.$data["StrLockKey"].'</strLockKey>                <company>'.$company.'</company>            </ApplyResponse>        ';        return $xml_content;    }    /*     * 投保天安     */    public function TA($id,$data,$insureType=null) {        $uri =  Yii::app()->params['Tianan_toubao'];        $req_str = $this->TAxml($id,$data);        $startime=microtime(true);        $ret = $this->request_by_curl($uri,$req_str);        $endtime=microtime(true);        $alltime=$endtime-$startime;        $this->log("天安投保申请报文：".$req_str);        $this->log("天安投保返回报文：".$ret);        $this->log("天安投保反应时间（秒）：".$alltime);        $result = json_decode($ret);        $import = new ImportinfoF();        $import->approvaltrans_id = $id;        $import->cWaterNo = $data['waterNo'];        $import->cooperation = $data['cooperation'];        $return = array(            'waterNo' => $data['waterNo'],            'retCode' => '',            'retDesc' => '',            'policyNum' => '',            'transTime' => '',            'epolicyAddress' => '',        );        if( $result ) {            if ($result->retCode == "00") {                $import->policyNum = $result->policyNo;                $import->retCode = "00";                $import->retDesc = $result->returnMsg;                $import->startDate = $result->startDate;                $import->endDate = $result->endDate;                $import->policyStatus = $result->returnMsg;                $import->realDate = strtotime($result->transTime)?strtotime($result->transTime):time();                $import->strLockKey = $data['StrLockKey'];                $import->orderNo = $data['orderNo'];                $import->epolicyAddress = $result->epolicyAddress;                $import->in_company = "2";                $return['retCode'] = $result->retCode;                $return['retDesc'] = $result->returnMsg;                $return['policyNum'] = $result->policyNo;                $return['transTime'] = $result->transTime?$result->transTime:date('Y-m-d H:i:s');                $return['epolicyAddress'] = $result->epolicyAddress;                //新增分保记录                $third_party_code = $data['third_party_code'];                $model = CsProductCode::model()->findByAttributes(array('third_party_code'=>$third_party_code,'in_company'=>2));                $model->insure_number += 1;                $model->save();            } else {                $import->retCode = "11";                $import->retDesc = $result->returnMsg;                $import->startDate = $data['StartDate'];                $import->endDate = $data['EndDate'];                $import->policyStatus = "失败";                $import->realDate = time();                $import->strLockKey = $data['StrLockKey'];                $import->orderNo = $data['OrderNo'];                $import->in_company = "2";                $return['retCode'] = "11";                $return['retDesc'] = $result->returnMsg;            }        }else{            $import->retCode = "11";            $import->retDesc = '核心接口连接失败，请联系管理员';            $import->policyStatus = "失败";            $import->realDate = time();            $import->in_company = "2";            $return['retCode'] = "11";            $return['retDesc'] = '核心接口连接失败，请联系管理员';        }        $import->createTime = time();        $import->save(false);        $return['company'] = "2";        $company = 2;        if ($insureType == 'huo') {            echo $return_msg = $this->JSON($return);        }        if ($insureType == 'hang') {            echo $return_msg = $this->setInsureXml($data,$result,$company);        }        $this->log("同程承保返回报文：".$return_msg);    }    public function TPxml($id,$data) {        $appData = ApprovaltransF::model()->findByPk($id);        $holderData = PolicyholdersF::model()->findByPk($appData->proposer_id);        $insuedData = InsuredinfoF::model()->findAllByAttributes(array("approvaltrans_id"=>$appData->id));        $i=0;        $rationType = $data['insure_product_code'];        $insuredDataDtoList=array();        foreach ($insuedData  as $value) {            $insuredDataDtoList[$i]['insuredName']=$value->InsuedName;            $insuredDataDtoList[$i]['identifyType']=$value->InsuedZJType;            $insuredDataDtoList[$i]['identifyNumber']=$value->InsuedZJNo;            $insuredDataDtoList[$i]['mobile']=$value->InsuedMobile;            $insuredDataDtoList[$i]['birthday']=$value->birthday;            $insuredDataDtoList[$i]['sex']=$value->sex;            $insuredDataDtoList[$i]['insRelationApp']= $value->insRelationApp;            $i++;        }        $nonce = strtoupper(md5(uniqid(mt_rand(), true)));        $time = time();        $data = array(            "rationType" => $rationType,            "riskCode" => $rationType,            "startDate" => $appData->startDate,            "endDate" => $appData->endDate,            "inputDate" => $appData->inputDate,            "holderNum" => $appData->holderNum,            "waterNo" => $appData->waterNo,            "appDataDto" => array(                "applicantName" => $holderData->ApplicantName,                "identifyType" => $holderData->ApplicantZJType,                "identifyNumber" => $holderData->ApplicantZJNum,                "applicantType" => $holderData->ApplicantType,                "mobile" => $holderData->ApplicantMobile,                "sex" => $holderData->sex,                "birthday" => $holderData->birthday,            ),            "insuredDataDtoList" => $insuredDataDtoList,            "dynamicDto" => array(                "fieldAA"=>$appData->trip,                "fieldAB"=>$appData->date?date('Y-m-d', strtotime($appData->date)):"",                "fieldAC"=>$appData->OrderID,                "fieldAD"=>$appData->DepartureCity,                "fieldAE"=>$appData->ArrivalCity,                "fieldAF"=>$appData->CarNo,                "fieldAG"=>$appData->CarNum,                "fieldAH"=>$appData->address?$appData->address:'无法采集',                "fieldAI"=>$appData->school,                "fieldAJ"=>$appData->class,            ),        );        $key = Yii::app()->params['Taiping_key'];        $data = json_encode($data,JSON_UNESCAPED_UNICODE);        $sign = md5($data.$key);        $data .= $sign;        return $data;    }    public function TAxml($id,$data) {        $appData = ApprovaltransF::model()->findByPk($id);        $holderData = PolicyholdersF::model()->findByPk($appData->proposer_id);        $insuedData = InsuredinfoF::model()->findAllByAttributes(array("approvaltrans_id"=>$appData->id));        $i=0;        $rationType = $data['insure_product_code'];        $insuredDataDtoList=array();        foreach ($insuedData  as $value) {            $insuredDataDtoList[$i]['insuredName']=$value->InsuedName;            $insuredDataDtoList[$i]['identifyType']=$value->InsuedZJType;            $insuredDataDtoList[$i]['identifyNumber']=$value->InsuedZJNo;            $insuredDataDtoList[$i]['mobile']=$value->InsuedMobile;            $insuredDataDtoList[$i]['birthday']=$value->birthday;            $insuredDataDtoList[$i]['sex']=$value->sex;            $insuredDataDtoList[$i]['insRelationApp']= $value->insRelationApp;            $i++;        }        $nonce = strtoupper(md5(uniqid(mt_rand(), true)));        $time = time();        $data = array(            "requestHead" => array(                "cooperation" => "tongcheng",                "nonce" => $nonce,                "sign" => $this->getSign($nonce, $time),                "timestamp" => $time,                "tradeNo" => $time.rand(10000, 99999),                "tradeDate" => date("Y-m-d H:i:s"),            ),            "rationType" => $rationType,            "riskCode" => $rationType,            "startDate" => $appData->startDate,            "endDate" => $appData->endDate,            "inputDate" => $appData->inputDate,            "holderNum" => $appData->holderNum,            "waterNo" => $appData->waterNo,            "appDataDto" => array(                "applicantName" => $holderData->ApplicantName,                "identifyType" => $holderData->ApplicantZJType,                "identifyNumber" => $holderData->ApplicantZJNum,                "applicantType" => $holderData->ApplicantType,                "mobile" => $holderData->ApplicantMobile,                "sex" => $holderData->sex,                "birthday" => $holderData->birthday,            ),            "insuredDataDtoList" => $insuredDataDtoList,            "dynamicDto" => array(                "fieldAA"=>$appData->trip,                "fieldAB"=>$appData->date?date('Y-m-d', strtotime($appData->date)):"",                "fieldAC"=>$appData->OrderID,                "fieldAD"=>$appData->DepartureCity,                "fieldAE"=>$appData->ArrivalCity,                "fieldAF"=>$appData->CarNo,                "fieldAG"=>$appData->CarNum,                "fieldAH"=>$appData->address?$appData->address:'无法采集',                "fieldAI"=>$appData->school,                "fieldAJ"=>$appData->class,            ),        );        $data = json_encode($data);        return $data;    }    /*     * 退保     */    public function actionHangSurrender() {        // 接收投保报文        $data = trim(file_get_contents("php://input"));        if (empty($data)) {            $xml_content = '<?xml version="1.0" encoding="UTF-8"?>                <CancelResponse>                    <CWaterNo></CWaterNo>                    <policyNum></policyNum>                    <RetCode>11</RetCode>                    <ReturnMsg>入参为空</ReturnMsg>                    <Policy_status></Policy_status>                    <RealDate></RealDate>                </CancelResponse>                ';            echo $xml_content;            die();        }        $this->log($data);        $xml_parser = xml_parser_create();        if(!xml_parse($xml_parser,$data,true)){            xml_parser_free($xml_parser);            $xml_content = '<?xml version="1.0" encoding="UTF-8"?>                <CancelResponse>                    <CWaterNo></CWaterNo>                    <policyNum></policyNum>                    <RetCode>11</RetCode>                    <ReturnMsg>入参格式错误</ReturnMsg>                    <Policy_status></Policy_status>                    <RealDate></RealDate>                </CancelResponse>                ';            echo $xml_content;            die();        }        $data = simplexml_load_string($data);        $data = json_decode(json_encode((array) $data), true);        $field = array('PolicyNum','ProductCode');        foreach ($field as $key=>$value) {            if (empty($data[$value])) {                $xml_content = '<?xml version="1.0" encoding="UTF-8"?>                <CancelResponse>                    <CWaterNo>'.$data["CWaterNo"].'</CWaterNo>                    <policyNum>'.$data["PolicyNum"].'</policyNum>                    <RetCode>11</RetCode>                    <ReturnMsg>'.$value.'不能为空</ReturnMsg>                    <Policy_status></Policy_status>                    <RealDate></RealDate>                </CancelResponse>                ';                echo $xml_content;                die();            }        }        //保单验证        $ispolicyNo = ImportinfoF::model()->findByAttributes(array('policyNum'=>$data['PolicyNum']));        if(!$ispolicyNo){            $xml_content = '<?xml version="1.0" encoding="UTF-8"?>                <CancelResponse>                    <CWaterNo>'.$data["CWaterNo"].'</CWaterNo>                    <policyNum>'.$data["PolicyNum"].'</policyNum>                    <RetCode>11</RetCode>                    <ReturnMsg>该保单号不存在</ReturnMsg>                    <Policy_status></Policy_status>                    <RealDate></RealDate>                </CancelResponse>                ';            echo $xml_content;            die;        }        $isinsurance = ApprovaltransF::model()->findByAttributes(array('id'=>$ispolicyNo->approvaltrans_id));        //判断是否重复提交        $dist = Surrenderinfo::model()->findByAttributes(array(            'policyNo' => $data['PolicyNum'],            'cooperation' => 'tongcheng'        ));        if($dist){            $xml_content = '<?xml version="1.0" encoding="UTF-8"?>            <CancelResponse>                <CWaterNo>'.$dist->waterNo.'</CWaterNo>                <policyNum>'.$dist->policyNo.'</policyNum>                <RetCode>'.$dist->retCode.'</RetCode>                <ReturnMsg>'.$dist->returnMsg.'</ReturnMsg>                <Policy_status></Policy_status>                <RealDate>'.date('Y-m-d H:i:s',$dist->realDate).'</RealDate>            </CancelResponse>            ';           echo $xml_content;        }else{            $surrender = New Surrender;            $surrender->waterNo = $data['CWaterNo']?$data['CWaterNo']:null;            $surrender->policyNo = $data['PolicyNum'];            $surrender->productCode = $isinsurance->ProductCode;            $surrender->rationType = $isinsurance->rationType;            $surrender->startDate = $data['StartDate']?$data['StartDate']:null;            $surrender->endDate = $data['EndDate']?$data['EndDate']:null;            $surrender->premium = $data['Premium']?$data['Premium']:null;            $surrender->cancelReason = $data['CancelReason']?$data['CancelReason']:null;            $surrender->cooperation = 'tongcheng';            $surrender->createTime = time();            $surrender->save(false);            //退保            $import = ImportinfoF::model()->findByAttributes(array('policyNum'=>$data['PolicyNum']));            //投保公司            $data['waterNo'] = $data['CWaterNo'];            $data['policyNo'] = $data['PolicyNum'];            $data['cooperation'] = 'tongcheng';            if( $import ) {                $company = $import->in_company;                $data['in_company'] = $company;                switch ($company) {                    case "1":                        $this->sHX($surrender->id,$data,'hang');                        break;                    case "2":                        $this->sTA($surrender->id,$data,'hang');                        break;                    case "3":                        $this->sTP($surrender->id,$data,'hang');                        break;                }            }        }    }    /*     * 退保     */    public function actionHuoSurrender() {        // 接收投保报文        $data = trim(file_get_contents("php://input"));        //逻辑        if(!$data){            echo '{"waterNo":"","policyNo":"","retCode":"11","returnMsg":"无参数"}';die;        }        $this->log("同程退保申请报文：".$data);        $data = json_decode($data, true);        if(!$data){            echo '{"waterNo":"","policyNo":"","retCode":"11","returnMsg":"参数不是json格式"}';die;        }        $get = array('waterNo'=>$data['waterNo'],            'cooperation'=>$data['cooperation'],            'policyNo'=>$data['policyNo'],            'productCode'=>$data['productCode'],        );        //非空判断        foreach ($get as $key => $value) {            if($value == ''){                echo '{"waterNo":"","policyNo":"","retCode":"11","returnMsg":"缺少参数:'.$key.'"}';die;            }        }        //保单验证        $ispolicyNo = ImportinfoF::model()->findByAttributes(array('policyNum'=>$data['policyNo']));        if(!$ispolicyNo){            echo '{"waterNo":"","policyNo":"","retCode":"11","returnMsg":"该保单号不存在"}';die;        }        $isinsurance = ApprovaltransF::model()->findByAttributes(array('id'=>$ispolicyNo->approvaltrans_id));        //判断是否重复提交        $dist = Surrenderinfo::model()->findByAttributes(array(            'policyNo' => $data['policyNo'],            'cooperation' => $data['cooperation']        ));        if($dist){            $return['waterNo'] = $dist->waterNo;            $return['policyNo'] = $dist->policyNo;            $return['retCode'] = $dist->retCode;            $return['returnMsg'] = $dist->returnMsg;            $return['transTime'] = date('Y-m-d H:i:s',$dist->realDate);            echo $this->JSON($return);        }else{            $surrender = New Surrender;            $surrender->waterNo = $data['waterNo'];            $surrender->policyNo = $data['policyNo'];            $surrender->productCode = $isinsurance->ProductCode;            $surrender->rationType = $isinsurance->rationType;            $surrender->startDate = $data['startDate'];            $surrender->endDate = $data['endDate'];            $surrender->premium = $data['premium'];            $surrender->cancelReason = $data['cancelReason'];            $surrender->cooperation = $data['cooperation'];            $surrender->createTime = time();            $surrender->save(false);            //退保            $import = ImportinfoF::model()->findByAttributes(array('policyNum'=>$data['policyNo']));            //投保公司            if( $import ) {                $company = $import->in_company;                switch ($company) {                    case "1":                        $this->sHX($surrender->id,$data,'huo');                        break;                    case "2":                        $this->sTA($surrender->id,$data,'huo');                        break;                    case "3":                        $this->sTP($surrender->id,$data,'huo');                        break;                }            }        }    }    public function setSurrenderXml($data,$result,$company) {        if ($company == 3) {            $policyNum = $result['policyNo'];            $RetCode = $result['retCode'] == '0000'?'00':'11';            $ReturnMsg = $result['returnMsg'];        } else {            $policyNum = $result['PolicyNum'];            $RetCode = $result['retCode'];            $ReturnMsg = $result['returnMsg'];        }        if ($company == 2) {            $policyNum = $result['policyNo'];        }        if ($company == 1) {            $RealDate = $result['transTime'];            if (!isset($result['policyNo'])) {                $policyNum = $data['policyNo'];                $ReturnMsg = $result['retDesc'];            } else {                $policyNum = $result['policyNo'];                $ReturnMsg = $result['returnMsg'];            }        }        $RealDate = $result['transTime'];        $xml_content = '<?xml version="1.0" encoding="UTF-8"?>        <CancelResponse>            <CWaterNo>'.$data["CWaterNo"].'</CWaterNo>            <policyNum>'.$policyNum.'</policyNum>            <RetCode>'.$RetCode.'</RetCode>            <ReturnMsg>'.$ReturnMsg.'</ReturnMsg>            <Policy_status></Policy_status>            <RealDate>'.$RealDate.'</RealDate>        </CancelResponse>      ';        return $xml_content;    }    /**     * 华夏退保     */    public function sHX($id,$data,$insureType=null){        $uri =  Yii::app()->params['Huaxia_tuibao'];        $surrender = Surrender::model()->findByPk($id);        $model = CsProductCode::model()->findByAttributes(array('third_party_code'=>$surrender->productCode,'in_company'=>$data['in_company']));        $rationType = $model->insure_product_code;        $json = '{            "waterNo":"'.$data['waterNo'].'",            "policyNo":"'.$data['policyNo'].'",            "productCode":"'.$rationType.'",            "cancelReason":"接口保单注销",            "cooperation":"tongcheng"        }';        $json = json_encode(json_decode($json, true), JSON_UNESCAPED_UNICODE);        $nonce = substr(md5(microtime(1)), 0, 20);        $timestamp = str_replace(".", "", microtime(1));        $params['uid'] = "adpt_tongcheng";        $params['timestamp'] = $timestamp;        $params["nonce"] = $nonce;        $params["data"] = $json;        $signString = $this->getLinkString($params);        $key = Yii::app()->params['Huaxia_key'];;        $signature = md5($signString.$key);        $params['signature'] = $signature;        $startime=microtime(true);        $ch = curl_init();        curl_setopt($ch,CURLOPT_URL,$uri);        curl_setopt($ch,CURLOPT_POST, 1);        $request = http_build_query($params);        curl_setopt($ch,CURLOPT_POSTFIELDS, $request);        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);        $response = curl_exec($ch);        curl_close($ch);        $endtime=microtime(true);        $alltime=$endtime-$startime;        $this->log("华夏退保申请报文：".json_encode($params));        $this->log("华夏退保返回报文：".$response);        $this->log("华夏退保反应时间（秒）：".$alltime);        $result = json_decode($response,true);        $return = array(            'waterNo' => $data['waterNo'],        );        if(!$result){            $return['retCode'] = '11';            $return['returnMsg'] = '核心接口连接失败，请联系管理员';            $return['policyNo'] = $data['policyNo'];            $return['transTime'] = date('Y-m-d H:i:s');        }elseif (!$result['policyNo']) {            $return['retCode'] = '11';            $return['returnMsg'] = $result['retDesc'];            $return['policyNo'] = $data['policyNo'];            $return['transTime'] = date('Y-m-d H:i:s');        }else{            if (!isset($result['policyNo'])){                $returnMsg = $result['retDesc'];            } else {                $returnMsg = $result['returnMsg'];            }            $surrenderinfo = New Surrenderinfo;            $surrenderinfo->surrender_id = $surrender->id;            $surrenderinfo->cooperation = $data['cooperation'];            $surrenderinfo->waterNo = $data['waterNo'];            $surrenderinfo->policyNo = $result['policyNo'];            $surrenderinfo->realDate = strtotime($result['transTime']);            $surrenderinfo->policyStatus = $result['policyStatus'];            $surrenderinfo->retCode = $result['retCode'];            $surrenderinfo->returnMsg = $returnMsg;            $surrenderinfo->createTime = time();            $surrenderinfo->in_company = "1";            $surrenderinfo->save(false);            $return['policyNo'] = $result['policyNo'];            $return['retCode'] = $result['retCode'];            $return['returnMsg'] = $returnMsg;            $return['transTime'] = $result['transTime'];        }        if ($insureType == 'huo') {            echo $return_msg = $this->JSON($return);        }        if ($insureType == 'hang') {            echo $return_msg = $this->setSurrenderXml($data,$result,1);        }        $this->log("同程退保返回报文：".$return_msg);    }    public function sTP($id,$data,$insureType=null){        $surrender = Surrender::model()->findByPk($id);        $model = CsProductCode::model()->findByAttributes(array('third_party_code'=>$surrender->productCode,'in_company'=>$data['in_company']));        $rationType = $model->insure_product_code;        $nonce = strtoupper(md5(uniqid(mt_rand(), true)));        $time=time();        $arr = array(            "waterNo" => $data['waterNo'],            "policyNo" => $data['policyNo'],            "productCode" => $rationType,            "rationType" => $rationType,            "cancelReason" => '太平接口保单注销',        );        $key = Yii::app()->params['Taiping_key'];        $arr = json_encode($arr,JSON_UNESCAPED_UNICODE);        $sign = md5($arr.$key);        $arr .= $sign;        $url =  Yii::app()->params['Taiping_tuibao'];        $startime=microtime(true);        $ret = $this->request_by_curl($url,$arr);        $endtime=microtime(true);        $alltime=$endtime-$startime;        $this->log("太平退保申请报文：".$arr);        $this->log("太平退保返回报文：".$ret);        $this->log("太平退保返回时间(秒)：".$alltime);        $result = json_decode($ret,true);        $return = array(            'waterNo' => $data['waterNo'],        );        if(!$result){            $return['retCode'] = '11';            $return['returnMsg'] = '核心接口连接失败，请联系管理员';        }elseif (!$result['policyNo']) {            $return['retCode'] = '11';            $return['returnMsg'] = '核心接口返回异常，请联系管理员';        }else{            $surrenderinfo = New Surrenderinfo;            $surrenderinfo->surrender_id = $surrender->id;            $surrenderinfo->cooperation = $data['cooperation'];            $surrenderinfo->waterNo = $data['waterNo'];            $surrenderinfo->policyNo = $result['policyNo'];            $surrenderinfo->realDate = strtotime($result['transTime']);            $surrenderinfo->policyStatus = $result['policyStatus'];            $surrenderinfo->retCode = $result['retCode']=='0000'?'00':'11';            $surrenderinfo->returnMsg = $result['returnMsg'];            $surrenderinfo->createTime = time();            $surrenderinfo->in_company = "3";            $surrenderinfo->save(false);            $return['policyNo'] = $result['policyNo'];            $return['retCode'] = $result['retCode']=='0000'?'00':'11';            $return['returnMsg'] = $result['returnMsg'];            $return['transTime'] = $result['transTime'];        }        if ($insureType == 'huo') {            echo $return_msg = $this->JSON($return);        }        if ($insureType == 'hang') {            echo $return_msg = $this->setSurrenderXml($data,$result,3);        }        $this->log("同程退保返回报文：".$return_msg);    }    public function sTA($id,$data,$insureType=null){        $surrender = Surrender::model()->findByPk($id);        $model = CsProductCode::model()->findByAttributes(array('third_party_code'=>$surrender->productCode,'in_company'=>$data['in_company']));        $rationType = $model->insure_product_code;        $nonce = strtoupper(md5(uniqid(mt_rand(), true)));        $time=time();        $arr = array(//            "requestHead" => array(//            "cooperation" => "tongcheng",//            "nonce" => $nonce,//            "sign" => $this->getSign($nonce, $time),//            "timestamp" => $time,//            "tradeNo" => $time.rand(10000, 99999),//            "tradeDate" => date("Y-m-d H:i:s"),//        ),            "waterNo" => $data['waterNo'],            "policyNo" => $data['policyNo'],            "productCode" => $rationType,            "rationType" => $rationType,            "cancelReason" => '天安接口保单注销',        );        $arr = json_encode($arr);        $url =  Yii::app()->params['Tianan_tuibao'];        $startime=microtime(true);        $ret = $this->request_by_curl($url,$arr);        $endtime=microtime(true);        $alltime=$endtime-$startime;        $this->log("天安退保申请报文：".$arr);        $this->log("天安退保返回报文：".$ret);        $this->log("天安退保返回时间(秒)：".$alltime);        $result = json_decode($ret,true);        $return = array(            'waterNo' => $data['waterNo'],        );        if(!$result){            $return['retCode'] = '11';            $return['returnMsg'] = '核心接口连接失败，请联系管理员';        }elseif (!$result['policyNo']) {            $return['retCode'] = '11';            $return['returnMsg'] = '核心接口返回异常，请联系管理员';        }else{            $surrenderinfo = New Surrenderinfo;            $surrenderinfo->surrender_id = $surrender->id;            $surrenderinfo->cooperation = $data['cooperation'];            $surrenderinfo->waterNo = $data['waterNo'];            $surrenderinfo->policyNo = $result['policyNo'];            $surrenderinfo->realDate = strtotime($result['transTime'])?strtotime($result['transTime']):time();            $surrenderinfo->policyStatus = $result['policyStatus'];            $surrenderinfo->retCode = $result['retCode'];            $surrenderinfo->returnMsg = $result['returnMsg'];            $surrenderinfo->createTime = time();            $surrenderinfo->in_company = "2";            $surrenderinfo->save(false);            $return['policyNo'] = $result['policyNo'];            $return['retCode'] = $result['retCode'];            $return['returnMsg'] = $result['returnMsg'];            $return['transTime'] = $result['transTime']?$result['transTime']:time();        }        if ($insureType == 'huo') {            echo $return_msg = $this->JSON($return);        }        if ($insureType == 'hang') {            echo $return_msg = $this->setSurrenderXml($data,$result,2);        }        $this->log("同程退保返回报文：".$return_msg);    }    public function request_by_curl($remote_server,$post_string,$ssl=false){        if(function_exists('curl_init')){            $ch = curl_init();            $header[] = "Content-type: text/xml";//定义content-type为xml            curl_setopt($ch,CURLOPT_URL,$remote_server);//             curl_setopt($ch, CURLOPT_TIMEOUT, 5);            curl_setopt($ch,CURLOPT_POST, 1);            curl_setopt($ch,CURLOPT_POSTFIELDS,$post_string);            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);            if($ssl){                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);            }            $data = curl_exec($ch);            curl_close($ch);            return $data;        }else{            return '请先安装curl';        }    }    //日志    private function log($content) {        $path = "log/".date("Y-m-d");        if (!file_exists($path)) {            mkdir($path);        }        $path .= "/rizhi.log";        $open=fopen($path,"a");        fwrite($open,date('Y-m-d H:i:s').':'.$content."\r\n");        fclose($open);    }    function getSign($nonce,$time){        $token =  Yii::app()->params['Newjk_token'];        $data = array($token, $nonce, $time);        sort($data, SORT_STRING);        $sign_orign = implode('',$data);        return $sign_haxi = sha1($sign_orign);    }    //判断是否为身份证    function idcard($card) {        $card = $this->to18Card($card);        if (strlen($card) != 18) {            return false;        }        $cardBase = substr($card, 0, 17);        return ($this->getVerifyNum($cardBase) == strtoupper(substr($card, 17, 1)));    }    //格式化15位身份证号码为18位    function to18Card($card) {        $card = trim($card);        if (strlen($card) == 18) {            return $card;        }        if (strlen($card) != 15) {            return false;        }        // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码        if (array_search(substr($card, 12, 3), array('996', '997', '998', '999')) !== false) {            $card = substr($card, 0, 6).'18'.substr($card, 6, 9);        } else {            $card = substr($card, 0, 6).'19'.substr($card, 6, 9);        }        $card = $card.$this->getVerifyNum($card);        return $card;    }    // 计算身份证校验码，根据国家标准gb 11643-1999    function getVerifyNum($cardBase) {        if (strlen($cardBase) != 17) {            return false;        }        // 加权因子        $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);        // 校验码对应值        $verify_number_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');        $checksum = 0;        for ($i = 0; $i < strlen($cardBase); $i++) {            $checksum += substr($cardBase, $i, 1) * $factor[$i];        }        $mod = $checksum % 11;        $verify_number = $verify_number_list[$mod];        return $verify_number;    }    //生日和性别提取    function sexIDCard($IDCard) {        if (strlen($IDCard) == 18) {            return $this->check18sex($IDCard);        } elseif ((strlen($IDCard) == 15)) {            return $this->check15sex($IDCard);        } else {            return false;        }    }    function check18sex($IDCard) {        $num = intval(substr($IDCard,16,1));        if(($num%2) == 0) {            return "02";        } else {            return "01";        }    }    function check15sex($IDCard) {        $num = intval(substr($IDCard,14,1));        if(($num%2) == 0) {            return "02";        } else {            return "01";        }    }    function birthIDCard($IDCard) {        if (strlen($IDCard) == 18) {            return $this->check18birthday($IDCard);        } elseif ((strlen($IDCard) == 15)) {            $IDCard = $this->convertIDCard15to18($IDCard);            return $this->check18birthday($IDCard);        } else {            return false;        }    }    function check18birthday($IDCard) {        $tyear= substr($IDCard,6,4);        $tmonth= substr($IDCard,10,2);        $tday= substr($IDCard,12,2);        return $tyear."-".$tmonth."-".$tday;    }    function convertIDCard15to18($IDCard) {        if (strlen($IDCard) != 15) {            return false;        } else {            // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码            if (array_search(substr($IDCard, 12, 3), array('996', '997', '998', '999')) !== false) {                $IDCard = substr($IDCard, 0, 6) . '18' . substr($IDCard, 6, 9);            } else {                $IDCard = substr($IDCard, 0, 6) . '19' . substr($IDCard, 6, 9);            }        }        $IDCard = $IDCard . $this->calcIDCardCode($IDCard);        return $IDCard;    }    // 解决json中文乱码    function arrayRecursive(&$array, $function, $apply_to_keys_also = false)    {        static $recursive_counter = 0;        if (++$recursive_counter > 1000) {            die('possible deep recursion attack');        }        foreach ($array as $key => $value) {            if (is_array($value)) {                arrayRecursive($array[$key], $function, $apply_to_keys_also);            } else {                $array[$key] = $function($value);            }            if ($apply_to_keys_also && is_string($key)) {                $new_key = $function($key);                if ($new_key != $key) {                    $array[$new_key] = $array[$key];                    unset($array[$key]);                }            }        }        $recursive_counter--;    }    function JSON($array) {        $this-> arrayRecursive($array, 'urlencode', true);        $json = json_encode($array);        return urldecode($json);    }    //根据产品来分保    private function getTargetCompany($thirdPartyCode) {        $products = CsProductCode::model()->findAllByAttributes(array("third_party_code"=>$thirdPartyCode));        if (count($products) > 1) {            $total_insure_number = 0;            $proportion = array();            foreach ($products as $product) {                //这个产品的所有保司的总承包数量                $total_insure_number += $product->insure_number;                $proportion[$product->in_company]['base_proportion'] = floatval($product->proportion);            }            foreach ($products as $product) {                $proportion[$product->in_company]['current_proportion'] = $product->insure_number/$total_insure_number * 100;                //分保的情况超过该配置的十分之九,警戒线                if ($proportion[$product->in_company]['current_proportion'] >= $proportion[$product->in_company]['base_proportion']) {                    $more_half[$product->in_company] = $proportion[$product->in_company]['base_proportion'] - $proportion[$product->in_company]['current_proportion'];                } else {                    $less_half[$product->in_company] = $product->proportion;                }            }            //如果less_half 有值得话,优先            if ($less_half) {                $rand = array();                $max = 0;                foreach ($less_half as $key=>$value) {                    if (intval($value) > $max) {                        $max = intval($value);                    }                    for ($i=0;$i<intval($value);$i++) {                        $rand[] = $key;                    }                }                shuffle($rand);                $num = rand(0,($max-1));                $in_company = $rand[$num];            } else {                arsort($more_half,SORT_NUMERIC);                $in_company = key($more_half);            }        }        if (count($products) == 1) {            $in_company = $products[0]->in_company;        }        $product = CsProductCode::model()->findByAttributes(array("third_party_code"=>$thirdPartyCode,'in_company'=>$in_company));        return array(            'in_company' => $in_company,            'product_code' => $product->insure_product_code,        );    }}